package com.huayu.languo.controller.app;

import com.huayu.languo.controller.base.AbstractBaseAppController;
import com.huayu.languo.handler.service.SpUserService;
import com.huayu.languo.model.anno.ReqMappingRestController;
import com.huayu.languo.model.dto.ResultDto;
import com.huayu.languo.model.enums.ResultCode;
import com.huayu.languo.model.excp.BizException;
import com.huayu.languo.model.po.SpUser;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@ReqMappingRestController("u")
public class LoginController extends AbstractBaseAppController {

    @Resource
    private SpUserService spUserService;

    @RequestMapping("/login")
    public ResultDto login(@CookieValue(required = false, value = "JSESSIONID") String jsessionId, @CookieValue(required = false, value = "SESSION") String sessionID) {
        logger.info("【login】JSESSIONID [{}]  SESSION [{}]", jsessionId, sessionID);

        //从 请求里取出 帐号 密码 信息，查询用户
        SpUser spUser = spUserService.getById(1L);
        if (spUser != null) {
            // redis session 有设置过期时间 30 min
            HttpSession session = getSession();
            session.setAttribute("userInfo", spUser);
            logger.info("【succ login 】session.getId [{}]", session.getId());
            return ResultDto.success();
        } else {
            throw new BizException(ResultCode.UNAUTHORIZED_401, null, "帐号或密码错误");
        }
    }

    @RequestMapping(value = "/getLoginUserInfo")
    public ResultDto get() {
        HttpSession session = getSession();
        logger.info("【login getUserInfo 】session.getId [{}]", session.getId());
        Object spUser = session.getAttribute("userInfo");
        if (spUser != null) {
            return ResultDto.success(spUser);
        } else {
            throw new BizException(ResultCode.UNAUTHORIZED_401, null, "请重新登录");
        }
    }
}
